package org.example.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.*;

/**
 * @author mayingfa
 */
@Slf4j
public class ConfigLoader {
    private final Set<String> locations;

    public ConfigLoader(Set<String> locations) {
        this.locations = locations;
    }

    public Properties loadProperties() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

        List<Resource> resources = new ArrayList<>();
        for (String location : locations) {
            Resource resource = resourceResolver.getResource(location);
            if (resource.exists()) {
                resources.add(resource);
            }
        }

        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocations(resources.toArray(new Resource[0]));
        try {
            propertiesFactoryBean.afterPropertiesSet();
            return propertiesFactoryBean.getObject();
        } catch (IOException e) {
            log.error("加载配置文件失败", e);
            return new Properties();
        }
    }

    /**
     * 默认按照以下顺序加载配置文件，后面加载的会覆盖之前加载的，所以加载顺序越低，优先级越高
     * 1. jar包内config目录                 优先级 低
     * 2. jar包内
     * 3. jar包同级目录下config目录
     * 4. jar包同级目录                     优先级 高
     *
     * @param propertiesFile 配置文件名称
     * @return 配置文件路径
     */
    public static Set<String> getDefaultLoadOrder(String propertiesFile) {
        Assert.hasText(propertiesFile, "配置文件不允许为空");

        String[] locations = new String[]{
                "classpath:/" + propertiesFile,
                "classpath:/config/" + propertiesFile,
                "file:./" + propertiesFile,
                "file:./config/" + propertiesFile
        };
        return new LinkedHashSet<>(Arrays.asList(locations));
    }
}
